<template>
  <div class="big-div" :style="{ backgroundImage: `url(${backgroundUrl})` }">
    <div style="align-items: center; font-size: larger">
      {{roomName}}
    </div>
    <br>
    <br>
    <el-row>
      <el-col :span="3">
      </el-col>
      <el-col :span="14">
        <div style="display: flex; flex-direction: row">
          <JwChat :taleList="list" @enter="bindEnter" @clickTalk="talkEvent" v-model="inputMsg"
                :toolConfig="tool" :config="config"  scrollType="scroll">
          <template slot="tools">
            <div style="width:20rem;text-align:right;" @click="diceEvent">
              <b slot="tools">掷骰</b>
            </div>
          </template>
        </JwChat>
          <JwChat-rightbox :config="rightConfig" @click="rightClick" />
        </div>
        <el-button type="danger" @click="quit">退出房间</el-button>
      </el-col>
      <el-col :span="7">
        <div style="display: flex; flex-direction: row">
          本团昵称：
          <el-input v-model="nickname"></el-input>
          <el-button type="primary" size="mini" @click="setNickname">更改</el-button>
        </div>
        <br>
        <br>
        <el-table
            :data="fileList"
            :key="fileTableKey"
            style="width: 100%"
            height="250">
          <el-table-column
              prop="filename"
              label="文件名"
              width="180">
          </el-table-column>
          <el-table-column
              label="下载">
            <template #default="scope">
              <el-button>
                <a :href="scope.row.url">下载</a>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <br>
    <br>
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%">
      <el-tabs type="border-card" v-model="diceInput.inputType">
        <el-tab-pane label="属性检定" name="attribute">
          <div style="display: flex; flex-direction: row;">
            属性名称：
            <el-input v-model="diceInput.attributeTest.name" placeholder="请输入内容"></el-input>
          </div>
          <div style="display: flex; flex-direction: row;">
            属性数值：
            <el-input v-model="diceInput.attributeTest.num" type="number" placeholder="请输入0-100的数字"></el-input>
          </div>
        </el-tab-pane>
        <el-tab-pane label="单纯掷骰" name="single">
          <div style="display: flex; flex-direction: row;">
            <el-input v-model="diceInput.singleDice.d" type="number"></el-input>
            &emsp;&emsp;&emsp;d&emsp;&emsp;&emsp;
            <el-input v-model="diceInput.singleDice.num" type="number"></el-input>
          </div>
        </el-tab-pane>
        <el-tab-pane label="SC检定" name="sc">
          <div style="display: flex; flex-direction: row;">
            剩余san值：
            <el-input v-model="diceInput.sc.scNum" type="number" placeholder="请输入0-100的数字"></el-input>
          </div>
          san值减少：
          <div style="display: flex; flex-direction: row;">
            成功：
            <el-input v-model="diceInput.sc.success.d" type="number"></el-input>
            &emsp;&emsp;&emsp;d&emsp;&emsp;&emsp;
            <el-input v-model="diceInput.sc.success.num" type="number"></el-input>
          </div>
          <div style="display: flex; flex-direction: row;">
            失败：
            <el-input v-model="diceInput.sc.fail.d" type="number"></el-input>
            &emsp;&emsp;&emsp;d&emsp;&emsp;&emsp;
            <el-input v-model="diceInput.sc.fail.num" type="number"></el-input>
          </div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="diceConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="上传图片"
               :visible.sync="uploadPictureDialogVisible"
               width="30%">
      <el-upload
          :http-request="uploadChatImage" accept="jpg" :show-file-list="false">
        <el-button size="small" type="primary">点击上传图片</el-button>
      </el-upload>
    </el-dialog>
    <div id="aplayer"></div>
    <uploader :key="uploader_key" :options="options"
              :autoStart="false"
              :file-status-text="statusText"
              class="uploader-example"
              @file-success="onFileSuccess" @file-added="filesAdded">
      <uploader-unsupport></uploader-unsupport>
      <uploader-drop>
        <uploader-btn :single="true" >选择文件</uploader-btn>
      </uploader-drop>
      <uploader-list></uploader-list>
    </uploader>
  </div>
</template>

<script>

import {useWebSocket} from "@/api/websocket";
import {getAvatar} from "@/api/user";
import {getMessage} from "@/api/message";
import {
  getAttribute,
  getFileList,
  getMusics,
  getNickname,
  getUsers,
  setNickname,
  stCard,
  uploadChatImage
} from "@/api/room";
import 'aplayer/dist/APlayer.min.css';
import APlayer from 'aplayer';
import SparkMD5 from "spark-md5";

export default {
  name: 'room',
  data() {
    return {
      ap: null,
      roomName: this.$route.params.roomName,
      messageListStart: 0,
      messageListLength: 50,
      uploadPictureDialogVisible: false,
      backgroundUrl: null,
      rid: 0,
      ws:'',
      inputMsg: '',
      list: [],
      tool: {
        show: ['img', ['掷骰','图片']],// 二级数组中放自定义名称
        showEmoji: true,
        callback: this.toolEvent
      },
      config: {
        historyConfig: {
          show: true,
          tip: '加载中',
          /**
           * @description: 点击加载更多的回调函数
           * @param {*}
           * @return {*}
           */
          callback: this.bindLoadHistory
        }
      },
      avatarUrl: null,
      dialogVisible: false,
      diceInput: {
        inputType: 'attribute',
        attributeTest: {
          name: null,
          num: 0
        },
        singleDice: {
          d: 0,
          num: 0
        },
        sc: {
          scNum: 0,
          success:{
            d: 0,
            num: 0
          },
          fail: {
            d: 0,
            num: 0
          }
        }
      },
      nickname: null,
      audios: [],
      info: {
        fixed: true, // 不开启吸底模式
        listFolded: true, // 折叠歌曲列表
        autoplay: false, // 开启自动播放
        preload: "auto", // 自动预加载歌曲
        loop: "all", // 播放循环模式、all全部循环 one单曲循环 none只播放一次
        order: "list", //  播放模式，list列表播放, random随机播放
      },
      rightConfig: {
        listTip: '当前在线',
        list: []
      },
      uploader_key: new Date().getTime(),//这个用来刷新组件--解决不刷新页面连续上传的缓存上传数据（注：每次上传时，强制这个值进行更改---根据自己的实际情况重新赋值）
      options: {},
      statusText: {
        success: "上传成功！",
        error: "出错了！",
        uploading: "上传中...",
        paused: "等待中...",
        waiting: "等待中..."
      },
      fileList: [],
      fileTableKey: 0,
    }
  },
  created() {
    this.init();
    this.getList(this.rid, this.messageListStart, this.messageListLength, this.list);
    this.getNickname();
    this.initUploadFile();
    this.initFileList();
  },
  mounted() {
    setTimeout(this.initAudio, 1000)
  },
  methods: {
    init(){
      this.rid = this.$route.params.rid
      this.ws = useWebSocket(this.handleMessage, window.sessionStorage.getItem("uid"), this.rid);
    },
    avatar(uid){
      let list = this.rightConfig.list
      for (let i = 0; i < list.length; i++){
        if (list[i].uid === uid){
          return list[i].img
        }
      }
    },
    getRoomMembers(){
      getUsers(this.rid)
          .then(response => {
            for (let i = 0; i < response.data.length; i++){
              let item = response.data[i];
              let user = {
                key: i,
                uid: item.uid,
                username: item.username
              }
              this.roomMembers.push(user)
            }
          })
    },
    quit() {
      this.close();
      this.$message({
        message: "退出房间",
        type: "success",
      })
      this.$router.back();
    },
    handleMessage(evt) {
      if (evt.data) {
        console.log("获取到的数据为:"+evt.data)
      }
      let msgObj = JSON.parse(evt.data)
      if (msgObj.type == "message") {
        const msg = {
          "date": msgObj.createTime,
          "text": {"text": msgObj.message},
          "mine": false,
          "name": msgObj.username,
          "img": this.avatar(msgObj.fromUserId)
        }
        console.log(msgObj)
        this.list.push(msg)
      }
      else if (msgObj.type == "changePic"){
        this.backgroundUrl = msgObj.src;
      }
      else if (msgObj.type == "addMusic"){
        this.ap.list.add(msgObj.audio)
      }
      else if (msgObj.type == 'dice'){
        getAvatar('dice')
            .then(response => {
              const msg = {
                "date": msgObj.createTime,
                "text": { "text": msgObj.message },
                "mine": false,
                "name": msgObj.username,
                "img": response.data
              }
              console.log(msg.img)
              this.list.push(msg)
            })
        return
      }
      else if (msgObj.type == 'getRoomMembers'){
        this.rightConfig.list = msgObj.members
        return;
      }
    },
    sendMsg(msg){
      this.ws.send(msg)
    },
    close(){
      this.ws.close();
    },
    testTimeOut(){
      this.timeOut = setTimeout(() => {
        console.log("reloading")
        this.getList();
        clearTimeout(this.timeOut);
        this.testTimeOut();
      },10000)
    },
    toolEvent (type, obj) {
      if (type === 'img'){
        this.uploadPictureDialogVisible = true
      }
    },
    uploadChatImage(param) {
      const formData = new FormData()
      formData.append("file", param.file)
      uploadChatImage(this.rid,formData)
          .then(response => {
            this.uploadPictureDialogVisible = false
            this.$message({
              message: "上传成功",
              type: "success",
            })
            getAvatar(window.sessionStorage.getItem("uid"))
                .then(resp => {
                  const msgObj = {
                    "date": this.getCurrentTime(),
                    "text": { "text": "<img data-src='"+response.data+"'/>" },
                    "mine": true,
                    "name": this.nickname,
                    "img": resp.data
                  }
                  console.log(msgObj.img)
                  this.list.push(msgObj)
                  let message = {
                    type: "message",
                    username: this.nickname,
                    createTime: msgObj.date,
                    message: "<img data-src='"+response.data+"'/>"
                  }
                  let messageStr = JSON.stringify(message)
                  this.sendMsg(messageStr)
                })
          })
    },
    bindEnter (e) {
      console.log(e)
      const msg = this.inputMsg
      if (!msg) return;
      const msgObj = {
        "date": this.getCurrentTime(),
        "text": { "text": msg },
        "mine": true,
        "name": window.sessionStorage.getItem("username"),
        "img": this.avatar(window.sessionStorage.getItem("uid"))
      }
      console.log(msgObj.img)
      this.list.push(msgObj)
      let message = {
        type: "message",
        username: window.sessionStorage.getItem("username"),
        createTime: msgObj.date,
        message: msg
      }
      let messageStr = JSON.stringify(message)
      this.sendMsg(messageStr)
      let reg = /\.\D+/ig
      if (reg.exec(msg)['index'] == 0){
        this.dice(msg)
      }
    },
    diceEvent()  {
      console.log('dice')
      this.dialogVisible = true
    },
    talkEvent (play) {
      console.log(play)
      if (play.data.isAdd == true){
        this.applierUid = play.data.applierUid;
        this.applyRid = play.data.rid;
        this.dialogVisible = true;
        this.dialogTitle = "申请加入";
        this.dialogMessage = play.data.text;
      }
    },
    getList(rid,start,length){
      getMessage(window.sessionStorage.getItem("uid"),rid, start, length)
          .then(response => {
            this.list = response.data
          })
    },
    bindLoadHistory () {
      console.log("loading history")
      this.messageListStart += this.messageListLength;
      this.messageListLength += 250;
      getMessage(window.sessionStorage.getItem("uid"),this.rid,this.messageListStart,this.messageListLength)
          .then(response => {
            let list = response.data
            this.list = list.concat(this.list)
          })
    },
    getCurrentTime() {
      //获取当前时间并打印
      let _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth()+1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
      _this.gettime = yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
      return(_this.gettime)
    },
    diceConfirm () {
      this.dialogVisible = false;
      let msg = null;
      console.log(this.diceInput.inputType)
      if (this.diceInput.inputType == 'attribute') {
        let random = Math.floor(Math.random() * 100 + 1);
        let name = this.diceInput.attributeTest.name;
        let num = this.diceInput.attributeTest.num;
        let msgM = '进行' + name + '检测，属性值为'+ num +'。rd100=' + random;
        if (random <= 5) {
          msg = msgM + '，大成功';
        } else if (random <= Math.floor(num / 5)) {
          msg = msgM + '，极难成功';
        } else if (random <= Math.floor(num / 2)) {
          msg = msgM + '，困难成功';
        } else if (random <= num) {
          msg = msgM + '，成功';
        } else if (random <= 95) {
          msg = msgM + '，失败';
        } else {
          msg = msgM + '，大失败';
        }
      }
      else if (this.diceInput.inputType == 'single') {
        let d = this.diceInput.singleDice.d;
        let num = this.diceInput.singleDice.num;
        let result = 0;
        msg = d+'d'+num+'=';
        for (let i = 0; i < d; i++){
          let random = Math.floor(Math.random() * num + 1);
          result += random;
          msg += random+'+';
        }
        msg = msg.substring(0, msg.length-1)
        msg += '='+result
        console.log(msg)
      }
      else if (this.diceInput.inputType == 'sc') {
        let random = Math.floor(Math.random() * 100 + 1);
        let scNum = this.diceInput.sc.scNum;
        let successD = this.diceInput.sc.success.d;
        let successNum = this.diceInput.sc.success.num;
        let failD = this.diceInput.sc.fail.d;
        let failNum = this.diceInput.sc.fail.num;
        let msgM = '进行SC检定，剩余san值为'+ scNum +'。rd100=' + random;
        if (random <= 5) {
          msg = msgM + '，大成功。损失san值'+successD+'点';
        } else if (random <= scNum) {
          msg = msgM + '，成功。';
          let result = 0;
          for (let i = 0; i < successD; i++){
            result += Math.floor(Math.random() * successNum + 1);
          }
          msg += '损失san值'+result+'点';
        } else if (random <= 95) {
          msg = msgM + '，失败。';
          let result = 0;
          for (let i = 0; i < failD; i++){
            result += Math.floor(Math.random() * failNum + 1);
          }
          msg += '损失san值'+result+'点';
        } else {
          msg = msgM + '，大失败。';
          let result = failD * failNum;
          msg += '损失san值'+result+'点';
        }
      }
      getAvatar('dice')
          .then(response => {
            const msgObj = {
              "date": this.getCurrentTime(),
              "text": { "text": msg },
              "mine": false,
              "name": '骰娘',
              "img": response.data
            }
            console.log(msgObj.img)
            this.list.push(msgObj)
            let message = {
              dice: true,
              username: '骰娘',
              createTime: msgObj.date,
              message: msg
            }
            let messageStr = JSON.stringify(message)
            this.sendMsg(messageStr)
          })
    },
    getNickname(){
      getNickname(this.rid, window.sessionStorage.getItem("uid"))
          .then(response =>{
            if (response.data == null){
              this.nickname = window.sessionStorage.getItem("username")
            } else {
              this.nickname = response.data.nickname
            }
            console.log(this.nickname)
          })
    },
    setNickname() {
      setNickname(this.rid, window.sessionStorage.getItem("uid"), this.nickname)
          .then(response => {
            this.$message({
              message: "设置成功",
              type: "success",
            })
          })
    },
    initAudio() {
      // 创建一个音乐播放器实例，并挂载到DOM上，同时进行相关配置
      this.ap = new APlayer({
        container: document.getElementById("aplayer"),
        audio: this.audios, // 音乐信息
        ...this.info, // 其他配置信息
      });
      getMusics(this.rid)
          .then(response => {
            this.ap.list.add(response.data)
          })
    },
    dice(diceStr){
      let rid = this.rid
      let uid = window.sessionStorage.getItem("uid")
      let username = this.nickname
      let regAttributeTest = /\.ra\s?\D+/ig
      let regSingleDice = /\.rd\s?\d+/ig
      let regMultiDice = /\.r\s?[\d+d\d+\+]+/ig
      let regCoc = /\.coc\s?\d*/ig
      let regSt = /\.st .+/ig
      if (regAttributeTest.test(diceStr)){
        let reg = /\s\D+/
        let attributeName = reg.exec(diceStr)[0].replaceAll(" ","")
        getAttribute(this.rid,window.sessionStorage.getItem("uid"),attributeName)
            .then(response => {
              let value = response.data
              let diceMsg = ""
              let result =Math.floor(Math.random() * 100)+1
              if (value === null){
                diceMsg = "无此属性"
              } else if (result > 95){
                diceMsg = username+"进行"+attributeName+"检定：1d100="+result+"。大失败。"
              } else if (result > value){
                diceMsg = username+"进行"+attributeName+"检定：1d100="+result+"。失败。"
              } else if (result > value / 2){
                diceMsg = username+"进行"+attributeName+"检定：1d100="+result+"。成功。"
              } else if (result > value / 5){
                diceMsg = username+"进行"+attributeName+"检定：1d100="+result+"。困难成功。"
              } else if (result > 5){
                diceMsg = username+"进行"+attributeName+"检定：1d100="+result+"。极难成功。"
              } else {
                diceMsg = username+"进行"+attributeName+"检定：1d100="+result+"。大成功。"
              }
              getAvatar('dice')
                  .then(response => {
                    const msgObj = {
                      "date": this.getCurrentTime(),
                      "text": {"text": diceMsg},
                      "mine": false,
                      "name": '骰娘',
                      "img": response.data
                    }
                    this.list.push(msgObj)
                    let message = {
                      type: 'dice',
                      username: '骰娘',
                      createTime: msgObj.date,
                      message: diceMsg
                    }
                    let messageStr = JSON.stringify(message)
                    this.sendMsg(messageStr)
                  })
            })
      }
      else if (regSingleDice.test(diceStr)){
        let reg = /\d+/ig
        let num = reg.exec(diceStr)[0]
        let result =Math.floor(Math.random() * num)+1
        let diceMsg = username+"掷骰：1d"+num+"= "+result
        getAvatar('dice')
            .then(response => {
              const msgObj = {
                "date": this.getCurrentTime(),
                "text": {"text": diceMsg},
                "mine": false,
                "name": '骰娘',
                "img": response.data
              }
              this.list.push(msgObj)
              let message = {
                type: 'dice',
                username: '骰娘',
                createTime: msgObj.date,
                message: diceMsg
              }
              let messageStr = JSON.stringify(message)
              this.sendMsg(messageStr)
            })
      }
      else if (regMultiDice.test(diceStr)){
        let reg = /\d+d\d+/ig
        let arr = diceStr.match(reg)
        let msg = username+'掷骰：'
        let diceMsg = ''
        let resultMsg = ''
        let result = 0
        for (let i = 0; i < arr.length; i++){
          let str = arr[i]
          let d = str.split("d")[0]
          let num = str.split("d")[1]
          diceMsg += d+'d'+num+'+'
          resultMsg += '('
          for (let j = 0; j < d; j++){
            let r =Math.floor(Math.random() * num)+1
            resultMsg += r+'+'
            result += r
          }
          resultMsg = resultMsg.substring(0,resultMsg.length-1)
          resultMsg += ')+'
        }
        resultMsg = resultMsg.substring(0,resultMsg.length-1)
        diceMsg = diceMsg.substring(0,diceMsg.length-1)
        msg += diceMsg+'='
        msg += resultMsg
        msg += '='+result
        diceMsg = msg
        getAvatar('dice')
            .then(response => {
              const msgObj = {
                "date": this.getCurrentTime(),
                "text": {"text": diceMsg},
                "mine": false,
                "name": '骰娘',
                "img": response.data
              }
              this.list.push(msgObj)
              let message = {
                type: 'dice',
                username: '骰娘',
                createTime: msgObj.date,
                message: diceMsg
              }
              let messageStr = JSON.stringify(message)
              this.sendMsg(messageStr)
            })
      }
      else if (regCoc.test(diceStr)){
        let reg = /\d+/ig
        let times = 1
        if (reg.exec(diceStr) != null){
          console.log(reg.exec(diceStr))
          times = reg.exec(diceStr)[0]
        }
        let arr = ['力量','体质','体型','敏捷','外貌','智力','意志','教育']
        let msg = "[COC7]人物卡作成:\n"
        for (let i = 0; i < times; i++){
          let total = 0
          let tmpMsg = ""
          for (let j = 0; j < arr.length; j++){
            let t1 = Math.floor(Math.random() * 6)+1
            let t2 = Math.floor(Math.random() * 6)+1
            let t3 = Math.floor(Math.random() * 6)+1
            let t = (t1+t2+t3)*5
            tmpMsg += arr[i]+":"+t+" "
            total += t
          }
          let t1 = Math.floor(Math.random() * 6)+1
          let t2 = Math.floor(Math.random() * 6)+1
          let t3 = Math.floor(Math.random() * 6)+1
          let t = (t1+t2+t3)*5
          tmpMsg += "幸运:"+t+" 共计"+total+'/'+(total+t)+" "+(total/(total+t)).toFixed(4)*100+"%\n"
          msg += tmpMsg
        }
        msg = msg.substring(0,msg.length-1)
        let diceMsg = msg
        getAvatar('dice')
            .then(response => {
              const msgObj = {
                "date": this.getCurrentTime(),
                "text": {"text": diceMsg},
                "mine": false,
                "name": '骰娘',
                "img": response.data
              }
              this.list.push(msgObj)
              let message = {
                type: 'dice',
                username: '骰娘',
                createTime: msgObj.date,
                message: diceMsg
              }
              let messageStr = JSON.stringify(message)
              this.sendMsg(messageStr)
            })
      }
      else if (regSt.test(diceStr)){
        diceStr = diceStr.replace(".st ","")
        let reg = /\D+\d+/ig
        let arr = diceStr.match(reg)
        let responseEntry = {}
        for (let i = 0; i < arr.length; i++){
          let str = arr[i]
          let reg1 = /\D+/ig
          let reg2 = /\d+/ig
          let key = reg1.exec(str)[0]
          let value = reg2.exec(str)[0]
          responseEntry[key] = value
        }
        stCard(rid,uid,responseEntry)
            .then(response => {
              let diceMsg = "属性设定成功！"
              getAvatar('dice')
                  .then(response => {
                    const msgObj = {
                      "date": this.getCurrentTime(),
                      "text": {"text": diceMsg},
                      "mine": false,
                      "name": '骰娘',
                      "img": response.data
                    }
                    this.list.push(msgObj)
                    let message = {
                      type: 'dice',
                      username: '骰娘',
                      createTime: msgObj.date,
                      message: diceMsg
                    }
                    let messageStr = JSON.stringify(message)
                    this.sendMsg(messageStr)
                  })
            })
            .catch(error => {
              let diceMsg = "属性设定失败！"
              getAvatar('dice')
                  .then(response => {
                    const msgObj = {
                      "date": this.getCurrentTime(),
                      "text": {"text": diceMsg},
                      "mine": false,
                      "name": '骰娘',
                      "img": response.data
                    }
                    this.list.push(msgObj)
                    let message = {
                      type: 'dice',
                      username: '骰娘',
                      createTime: msgObj.date,
                      message: diceMsg
                    }
                    let messageStr = JSON.stringify(message)
                    this.sendMsg(messageStr)
                  })
            })
      }
    },
    //以下方法为文件上传以及文件列表展示的方法
    initUploadFile(){
      this.options = {
        target: `http://localhost:9001/room//chunkUpload/${this.rid}`,
        testChunks: false, //不校验
      };
    },
    onFileSuccess: function(rootFile, file, response, chunk) {
      // this.$refs.upload.files = [];
      // this.$refs.upload.fileList = [];
      getFileList(this.rid)
          .then(response => {
            console.log("更新文件列表")
            this.fileList = response.data
            this.fileTableKey = Math.random()
          })
      this.$message({
        message: "上传成功！",
        type: "success"
      })
    },
    computeMD5(file) {
      //大文件的md5计算时间比较长，显示个进度条
      const loading = this.$loading({
        lock: true,
        text: '正在计算MD5',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let fileReader = new FileReader();
      let time = new Date().getTime();
      let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
      let currentChunk = 0;
      const chunkSize = 10 * 1024 * 1000;
      let chunks = Math.ceil(file.size / chunkSize);
      let spark = new SparkMD5.ArrayBuffer();
      file.pause();
      loadNext();
      fileReader.onload = (e => {
        spark.append(e.target.result);
        if (currentChunk < chunks) {
          currentChunk++;
          loadNext();
          // 实时展示MD5的计算进度
          this.$nextTick(() => {
            console.log('校验MD5 '+ ((currentChunk/chunks)*100).toFixed(0)+'%')
          })
        } else {
          let md5 = spark.end();
          loading.close();
          this.computeMD5Success(md5, file);
          console.log(`MD5计算完毕：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${file.size} 用时：${new Date().getTime() - time} ms`);
        }
      });
      fileReader.onerror = function () {
        this.error(`文件${file.name}读取出错，请检查该文件`);
        loading.close();
        file.cancel();
      };
      function loadNext() {
        let start = currentChunk * chunkSize;
        let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
      }
    },
    computeMD5Success(md5, file) {
      file.uniqueIdentifier = md5;//把md5值作为文件的识别码
      file.resume();//开始上传
    },
    /**
     * 添加文件后触发
     * @param file
     * @param event
     */
    filesAdded(file, event){
      this.computeMD5(file)
    },
    initFileList(){
      getFileList(this.rid)
          .then(response => {
            console.log("更新文件列表")
            this.fileList = response.data
            this.fileTableKey = Math.random()
          })
    }
  },


}
</script>

<style scoped>
.big-div {
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0px;
  left: 0px;
}
</style>
